package cn.edu.sdu.sol.intake_system.service;

import cn.edu.sdu.sol.intake_system.model.po.Department;
import cn.edu.sdu.sol.intake_system.model.po.SysUser;
import cn.edu.sdu.sol.intake_system.model.po.UserType;
import cn.edu.sdu.sol.intake_system.model.vo.DataRequest;
import cn.edu.sdu.sol.intake_system.model.vo.DataResponse;
import cn.edu.sdu.sol.intake_system.repository.DepartmentRepository;
import cn.edu.sdu.sol.intake_system.repository.UserRepository;
import cn.edu.sdu.sol.intake_system.utils.JwtUtil;
import cn.edu.sdu.sol.intake_system.utils.VO;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class ImgService {

    private final VO vo = new VO();

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    UserRepository userRepository;

    @Autowired
    DepartmentRepository departmentRepository;

    private String uploadToImageHosting(byte[] imageBytes, String filename) throws IOException {
        String apiUrl = "https://www.imagehub.cc/api/1/upload"; // 替换为Chevereto图床的API URL
        String apiKey = "chv_I86d_59c574884ccb1c9e803b7d17ba359a4b23410c34470294b37014fe372609324bc0b126150d97fc5235ba7ae2201b962b2835e50cfeacb0e2f5a15a2db8877f86"; // 替换为你的API密钥

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("X-API-Key", apiKey);

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("source", new ByteArrayResource(imageBytes) {
            @Override
            public String getFilename() {
                return filename; // 设置所需的文件名
            }
        });

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.POST, requestEntity, String.class);

        if (response.getStatusCode() == HttpStatus.OK) {
            // 解析响应JSON以获取图片URL
            // 这里假设响应格式类似于：{"image":{"url":"image_url"}}
            JsonObject jsonObject = JsonParser.parseString(response.getBody()).getAsJsonObject();
            String imageUrl = jsonObject.getAsJsonObject("image").get("url").getAsString();
            return imageUrl;
        } else {
            throw new IOException("图片上传失败，状态码：" + response.toString());
        }
    }

    public DataResponse getHeadImage(String token) {
        token = token.substring(7);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        if (sysUser.isEmpty()) {
            return vo.messageError("用户不存在!");
        }
        SysUser user = sysUser.get();
        String url = user.getHeadImg();
        Map<String, String> picResult = new HashMap<>();
        picResult.put("imageUrl", url);
        return vo.data(picResult);
    }


    public DataResponse uploadHeadImage(MultipartFile file, String filename, String token) {
        try {
            // 1. 处理上传的图片文件
            byte[] imageBytes = file.getBytes();

            // 2. 调用图床API上传图片
            String imageUrl = uploadToImageHosting(imageBytes, filename);
            //System.out.println(imageUrl);

            token = jwtUtil.extractTokenFromHeader(token);
            String studentNum = jwtUtil.getStudentNumFromToken(token);
            Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
            if (sysUser.isEmpty()) {
                return vo.messageError("用户不存在!");
            }
            SysUser user = sysUser.get();
            user.setHeadImg(imageUrl);
            userRepository.saveAndFlush(user);
            // 返回上传结果或图片URL
            Map<String, String> picResult = new HashMap<>();
            picResult.put("imageUrl", imageUrl);
            return vo.data(picResult);
        } catch (IOException e) {
            e.printStackTrace();
            return vo.messageError("上传图片错误!");
        }
    }

    public DataResponse uploadDepartmentImage(MultipartFile file, String filename, String token, Integer departmentId) {
        try {

            token = jwtUtil.extractTokenFromHeader(token);
            String studentNum = jwtUtil.getStudentNumFromToken(token);
            Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
            assert sysUser.isPresent();
            // 1. 处理上传的图片文件
            byte[] imageBytes = file.getBytes();

            // 2. 调用图床API上传图片
            String imageUrl = uploadToImageHosting(imageBytes, filename);
            //System.out.println(imageUrl);

            SysUser user = sysUser.get();
            if (user.getRole() != UserType.ADMIN && user.getRole() != UserType.SUPER) {
                return vo.messageError("无权限!");
            }
            Optional<Department> optionalDepartment = departmentRepository.findDepartmentByDepartmentId(departmentId);
            if (optionalDepartment.isEmpty()) {
                return vo.messageError("无该部门!");
            }
            Department department = optionalDepartment.get();
            department.setCoverImg(imageUrl);
            departmentRepository.saveAndFlush(department);

            Map<String, String> picResult = new HashMap<>();
            picResult.put("imageUrl", imageUrl);
            return vo.data(picResult);
        } catch (IOException e) {
            e.printStackTrace();
            return vo.messageError("上传图片错误!");
        }
    }

    public DataResponse getDepartmentImage(String token, DataRequest dataRequest) {
        token = token.substring(7);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        if (sysUser.isEmpty()) {
            return vo.messageError("用户不存在!");
        }
        SysUser user = sysUser.get();
        Integer departmentId = dataRequest.getInteger("departmentId");
        Optional<Department> optionalDepartment = departmentRepository.findDepartmentByDepartmentId(departmentId);
        if (optionalDepartment.isEmpty()) {
            return vo.messageError("无该部门!");
        }
        Department department = optionalDepartment.get();
        String imageUrl = department.getCoverImg();
        Map<String, String> picResult = new HashMap<>();
        picResult.put("imageUrl", imageUrl);
        return vo.data(picResult);
    }

    public DataResponse getAllDepartmentImg(String token) {
        token = token.substring(7);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        if (sysUser.isEmpty()) {
            return vo.messageError("用户不存在!");
        }
        HashMap<Integer, Map<String, String>> data = new HashMap<>();

        List<Department> departments = departmentRepository.findAll();
        for(int i = 0; i < departments.size(); i++){
            Map<String, String> map = new HashMap<>();
            map.put(departments.get(i).getName(), departments.get(i).getCoverImg());
            data.put(i + 1, map);
        }
        return vo.data(data);
    }
}